<?php
/**
 * Date: 16/8/15
 * Time: 下午5:31
 */

namespace Dao6\Cache;


class FileCache implements ICache{

    private $_cache_dir = './.cache_files';

    public function __construct($cache_dir = '') {
        if(!empty($cache_dir)){
            $this->_cache_dir = $cache_dir;
        }
        if(!is_dir($this->_cache_dir)){
            mkdir($this->_cache_dir, 0777, true);
        }
    }

    public function set($name, $value, $exp = 0) {
        $save_filename = $this->getSaveFileName($name);
        file_put_contents($save_filename, serialize(array(
            'name'  => $name,
            'value' => $value,
            'time'  => time(),
            'exp'   => $exp
        )));
    }

    public function get($name, $defaultValue = null) {
        $save_filename = $this->getSaveFileName($name);
        if (file_exists($save_filename)) {
            $content = file_get_contents($save_filename);
            $content = unserialize($content);
            if (empty($content['exp']) || (time() - $content['time'] <= $content['exp'])) {
                return $content['value'];
            }
        }
        return $defaultValue;
    }

    private function getSaveFileName($name = ''){
        return $this->_cache_dir . DIRECTORY_SEPARATOR . md5($name) . '.cache';
    }
}